package com.starrtc.demo.imclient.clientHandler;

import com.starrtc.demo.imclient.ClientSender.LoginSender;
import com.starrtc.demo.imclient.client.ClientSession;
import com.starrtc.demo.imclient.iMcommon.bean.UserDTO;
import com.starrtc.demo.imclient.iMcommon.bean.msg.ProtoMsg;
import com.starrtc.demo.imclient.protoBuilder.HeartBeatMsgBuilder;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.TimeUnit;


@ChannelHandler.Sharable
public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    public static HeartBeatClientHandler instance;

    public static HeartBeatClientHandler getInstance(){
        if(instance == null){
            instance = new HeartBeatClientHandler();
            return instance;
        }
        return instance;
    }

    private HeartBeatClientHandler(){

    }

    //心跳的时间间隔，单位为s
    private static final int HEARTBEAT_INTERVAL = 100;

    //在Handler被加入到Pipeline时，开始发送心跳
    @Override
    public void handlerAdded(ChannelHandlerContext ctx)
            throws Exception {
        ClientSession session = ClientSession.getSession(ctx);
        UserDTO user = session.getUser();
        HeartBeatMsgBuilder builder =
                new HeartBeatMsgBuilder(user, session);

        ProtoMsg.Message message = builder.buildMsg();
        //发送心跳
        heartBeat(ctx, message);
    }

    //使用定时器，发送心跳报文
    public void heartBeat(final ChannelHandlerContext ctx,
                          final ProtoMsg.Message heartbeatMsg) {
        ctx.executor().schedule(new Runnable() {
            @Override
            public void run() {

                if (ctx.channel().isActive()) {
//                log.info(" 发送 HEART_BEAT  消息 to server");
                    ctx.writeAndFlush(heartbeatMsg);

                    //递归调用，发送下一次的心跳
                    heartBeat(ctx, heartbeatMsg);
                }
            }
        } , HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
    }

    /**
     * 接受到服务器的心跳回写
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断类型
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = pkg.getType();
        if (headType.equals(ProtoMsg.HeadType.HEART_BEAT)) {

//            log.info(" 收到回写的 HEART_BEAT  消息 from server");

            return;
        } else {
            super.channelRead(ctx, msg);

        }

    }

}
